<!-- 商品发布 - 商品详情 -->
<template>
  <ContentWrap>
    <div
      class="p-10px border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      付费会员协议
    </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="hideId" v-show="false">
        <el-input v-model="formData.payMemberConfigId" />
      </el-form-item>
      <el-form-item label="协议名称" prop="payMemberProtocolName" class="w-480px">
        <el-input v-model="formData.payMemberProtocolName" />
      </el-form-item>
      <!--富文本编辑器组件-->
      <el-form-item label="协议内容" prop="payMemberProtocol">
        <Editor v-model:modelValue="formData.payMemberProtocol" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm"> 保存 </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>
import Editor from '@/views/app/components/editor/index.vue'

import * as ConfigApi from '@/api/memberPaid/config'

defineOptions({ name: 'ProductpayMemberProtocolForm' })
const { t } = useI18n() // 国际化

const message = useMessage() // 消息弹窗

const formRef = ref() // 表单Ref
const formData = ref<ConfigApi.ConfigVO>({
  payMemberConfigId: undefined,
  payMemberProtocolName: '',
  payMemberProtocol: '' // 商品详情
})
// 表单规则
const rules = reactive({
  payMemberProtocolName: [required],
  payMemberProtocol: [required]
})

/** 富文本编辑器如果输入过再清空会有残留，需再重置一次 */
watch(
  () => formData.value.payMemberProtocol,
  (newValue) => {
    if ('<p><br></p>' === newValue) {
      formData.value.payMemberProtocol = ''
    }
  },
  {
    immediate: true
  }
)

/** 表单校验 */
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ConfigApi.ConfigVO
    await ConfigApi.saveConfig(data)
    message.success(t('common.updateSuccess'))
    getConfig()
  } finally {
    formLoading.value = false
  }
}
/** 获得付费会员配置 */
const getConfig = async () => {
  try {
    const data = await ConfigApi.getConfig()
    if (data === null) {
      return
    }
    formData.value = data
  } finally {
  }
}

onMounted(() => {
  getConfig()
})
</script>
